<template>
  <div>
    <a-space direction="vertical" fill>
      <a-button type="primary" long @click="handleClick">数据配置</a-button>
    </a-space>
    <a-drawer :width="500" :visible="visible" @ok="handleOk" @cancel="handleCancel" placement="left" unmountOnClose>
      <template #title> 绑定设备 </template>
      <a-row class="grid-demo">
        <a-col :span="24" style="margin-top: 50px;">
          <a-form :model="formDrawer.formModel" auto-label-width :rules="formDrawer.rules">
            <a-form-item field="deviceId" label="选择设备" :validate-trigger="['change', 'input']">
              <a-tree-select v-model="formDrawer.formModel.deviceId" :data="renderDeviceData"
                @change="fetchDeviceVarData" placeholder="请选择设备"
                :fieldNames="{ key: 'id', title: 'deviceName', children: 'children' }" :allow-search="true" allow-clear
                :filter-tree-node="filterTreeNode"></a-tree-select>
            </a-form-item>
            <a-form-item field="deviceProp" label="选择变量" :validate-trigger="['change', 'input']">
              <a-select v-model="formDrawer.formModel.deviceProp" :options="renderDeviceVarData"
                :fieldNames="{ value: 'varSn', label: 'varName', children: 'children' }" placeholder="请选择变量"
                allow-clear>
              </a-select>
            </a-form-item>
            <!-- v-if="formDrawer.formModel.isShowDevicePropType" -->
            <a-form-item  field="devicePropType" label="变量类型"
              :validate-trigger="['change', 'input']">
              <a-select v-model="formDrawer.formModel.devicePropType" placeholder="变量类型" allow-clear>
                <a-option v-for="item in renderPropType" :key="item.id" :value="Number(item.id)">
                  {{ item.value }}</a-option>
              </a-select>
            </a-form-item>
            <!-- v-if="formDrawer.formModel.isShowSvgNodeProp" -->
            <a-form-item  field="svgNodeProp" label="图形属性"
              :validate-trigger="['change', 'input']">
              <a-select v-model="formDrawer.formModel.svgNodeProp" placeholder="请选择图形属性" allow-clear>
                <a-option v-for="item in getHandItemProp()" :key="item.label" :value="item.value">
                  {{ item.label }}</a-option>
              </a-select>
            </a-form-item>
            <a-space direction="vertical" fill>
              <a-button type="primary" long @click="handleSave">保存配置</a-button>
            </a-space>
          </a-form>
        </a-col>
      </a-row>
    </a-drawer>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { listDeviceVarAll, listFusionGroup, addWebtopoSvgNode, listSvgNode, updateWebtopoSvgNode } from "../../../api/webtopo";
import { processSelectable } from "../../../utils/ruoyi";
import { Notification } from "@arco-design/web-vue";
/*************************** 变量区域 begin ***************************/
//抽屉显示隐藏
const visible = ref(false);
//组件参数
const props = defineProps({
  handItemInfo: {
    type: Object,
    default: () => { },
  },
  projectId: {
    type: String,
    default: "",
  },
  stationType: {
    type: Number,
    default: 0,
  },
});
//设备
const renderDeviceData = ref<any>([]);
//设备变量
const renderDeviceVarData = ref<any>([]);
//已绑定的数据
const renderSvgNodeData = ref<any>([]);

//变量类型
const renderPropType = ref<any>([
  { id: 1, value: "模拟量" }, { id: 2, value: "状态量" }
])



// 监听 WebSocket 数据变化
watch(props, (newVal:any) => {
  console.log("props watch=>",newVal);
});

/*************************** 变量区域 end ***************************/

/*************************** 方法区域 begin ***************************/
const generateFormDrawerModel = () => {
  return {
    visible: false,
    rules: {
      deviceId: [{ required: true, message: "请选择设备" }],
      deviceProp: [{ required: true, message: "请选择设备变量" }],
      devicePropType: [{ required: true, message: "请选择变量类型" }],
      svgNodeProp: [{ required: true, message: "请选择图形属性" }],
    },
    formModel: {
      id:0,
      deviceId: '',
      deviceProp: "",
      projectId: props.projectId,
      svgNodeId: props.handItemInfo.id,
      svgNodeProp: "",
      isShowSvgNodeProp: true,
      isShowDevicePropType: true,
      devicePropType: 1
    },
  };
};
const formDrawer = ref(generateFormDrawerModel());
/**
 * 新增绑定-打开抽屉
 */
const handleClick = async() => {
  visible.value = true;
  await fetchData();
};
/**
 * 确定
 */
const handleOk = () => {
  visible.value = false;
};
/**
 * 确定
 */
const handleCancel = () => {
  visible.value = false;
};

//获取组件参数
const getHandItemProp = () => {
  let temp_prop: { label: string; value: string }[] = [];
  for (const key in props.handItemInfo.props) {
    temp_prop.push({
      label: props.handItemInfo.props[key].title,
      value: `props.${key}.val`,
    });
  }
  return temp_prop;
};

/**
 * 保存配置
 */
const handleSave = async () => {
  console.log("handleSave=>", formDrawer.value.formModel);
  try {
    let res = null;
    if(formDrawer.value.formModel.id > 0){
      res = await updateWebtopoSvgNode(formDrawer.value.formModel);
    }else{
      res = await addWebtopoSvgNode(formDrawer.value.formModel);
    }
    notification(res);
    if (res.code == 200) {
      formDrawer.value = generateFormDrawerModel();
      await fetchSvgNodeData();
    }
  } catch (err) {

  }
}

/**
 * 设备搜索
 * @param searchValue 
 * @param nodeData 
 */
const filterTreeNode = (searchValue: any, nodeData: any) => {
  return nodeData.deviceName.toLowerCase().indexOf(searchValue.toLowerCase()) > -1;
}

/**
 * 获取设备列表
 */
const fetchDeviceData = async () => {
  try {
    const res = await listFusionGroup({ stationType: props.stationType });
    processSelectable(res.data);
    renderDeviceData.value = res.data;
  } catch { }
};

//获取变量列表
const fetchDeviceVarData = async () => {
  try {
    const res = await listDeviceVarAll({ deviceId: formDrawer.value.formModel.deviceId });
    if (res.code == 200) {
      renderDeviceVarData.value = res.data;
    }
  } catch (err) {

  }
}

const fetchSvgNodeData = async () => {
  try {
    let params: any = { projectId: props.projectId, svgNodeId: props.handItemInfo.id };
    let res = await listSvgNode(params);
    if (res.code == 200 && res.data && res.data.length == 1) {
      formDrawer.value.formModel = res.data[0];
      await fetchDeviceVarData();
    }
    // if (props.handItemInfo.tag == "text-vue") {
    //   //formDrawer.value
    //   formDrawer.value.formModel.isShowSvgNodeProp = true
    //   formDrawer.value.formModel.devicePropType = 1;
    //   formDrawer.value.formModel.isShowDevicePropType = false
    //   formDrawer.value.formModel.svgNodeProp = "props.text.val"
    // } else {
    //   formDrawer.value.formModel.isShowSvgNodeProp = false
    //   formDrawer.value.formModel.isShowDevicePropType = true
    // }
  } catch (err) {

  }
}


/**
 * 消息提示
 * @param res 通知数据
 */
const notification = (res: any) => {
  Notification[res.code === 200 ? 'success' : 'error']({
    title: '提示',
    content: res.msg
  })
}


/*************************** 方法区域 end ***************************/

const fetchData = async () =>{
  await fetchSvgNodeData();
  await fetchDeviceData();
}

</script>
<style scoped></style>
